<?php
    /* api 单文件版 */
    /**
    * mysql数据库连接
    **/
    class D
    {

        private $link; //数据库连接
        private $table; //表名
        private $prefix; //表前缀

        private $db_config = array(
             'DB_HOST'=>'qdm108629302.my3w.com',// //服务器地址
             'DB_NAME' => 'qdm108629302_db', // 数据库名
             'DB_USER' => 'qdm108629302', // 用户名
             'DB_PWD' => 'zsjnhfjlhsjyfj', // 密码
             'DB_PORT'=> '3306',
             'DB_ENCODE'=>'utf8',//编码
             'DB_PREFIX' => 'sw_' // 数据库表前缀
         );

         private $conn_sql = '';

        /**
         * 参数:表名 数据库配置数组 或 数据库配置文件路径 alter table 表名 convert to character set utf8;
         * @param $table
         * @param string $db_config_arr_path
         */

        function __construct($table = '',$db = '')
        {

            if($db!=''){
                $this->db_config["DB_NAME"] = $db;
            }
            $this->conn();
            $this->table = $this->prefix . $table;
        }


        /**
         * 连接数据库
         */
        private function conn()
        {
            $db_config = $this->db_config;
            $host = $db_config["DB_HOST"];
            $port = $db_config['DB_PORT'];
            $user = $db_config["DB_USER"];
            $pwd = $db_config["DB_PWD"];
            $db_name = $db_config["DB_NAME"];
            $db_encode = $db_config["DB_ENCODE"];
            $this->prefix = $db_config["DB_PREFIX"];
            try{
                $con = "mysql:host=$host;port=$port;dbname=$db_name";
                $this->link = new PDO($con,$user,$pwd,array(PDO::MYSQL_ATTR_INIT_COMMAND=>"set names '$db_encode'"));
            }catch (PDOException $e){
                echo "数据库连接出错";
            }

        }

        /**
         * 数据查询
         * 参数:sql条件 查询字段 使用的sql函数名
         * @param string $where
         * @param string $field
         * @param string $fun
         * @return array
         * 返回值:结果集 或 结果(出错返回空字符串)
         */
        public function select($where = '1', $field = "*", $table = '')
        {
            $rarr = array();

            $table = empty($table) ? $this->table : ($this->prefix . $table);

            $sqlStr = "select $field from $table where $where";
            $rt =  $this->link->query($sqlStr);
            while ($rt && $arr = $rt->fetch(PDO::FETCH_ASSOC)) {
                array_push($rarr, $arr);
            }

            return $rarr;
        }

        /**
         * 数据更新
         * 参数:sql条件 要更新的数据(字符串 或 关联数组)
         * @param $where
         * @param $data
         * @return bool
         * 返回值:语句执行成功或失败,执行成功并不意味着对数据库做出了影响
         */
        public function update($where, $data,$table = "")
        {
            $ddata = '';

            $table = empty($table) ? $this->table : ($this->prefix . $table);

            if (is_array($data)) {
                while (list($k, $v) = each($data)) {
                    if (empty($ddata)) {
                        $ddata = "$k='".addslashes($v)."'";

                    } else {
                        $ddata .= ",$k='".addslashes($v)."'";
                    }
                }
            } else {
                $ddata = $data;
            }
            //echo($ddata);
            $sqlStr = "update $table set $ddata where $where";
            //echo($sqlStr);
            return $this->link->exec($sqlStr);
        }

        /**
         * 数据添加
         * 参数:数据(数组 或 关联数组 或 字符串)
         * @param $data
         * @return int
         * 返回值:插入的数据的ID 或者 0
         */
        public function insert($data,$table = "")
        {
            $field = '';
            $idata = '';
            $table = empty($table) ? $this->table : ($this->prefix . $table);

            //echo( array_keys($data) !== range(0, count($data) - 1) ? 1 : 0);
            if (is_array($data) && array_keys($data) !== range(0, count($data) - 1)) {
                //关联数组
                while (list($k, $v) = each($data)) {
                    if (empty($field)) {
                        $field = "$k";
                        $idata = "'$v'";
                    } else {
                        $field .= ",$k";
                        $idata .= ",'$v'";
                    }
                }
                $sqlStr = "insert into $table($field) values ($idata)";

            } else {
                //非关联数组 或字符串
                if (is_array($data)) {
                    while (list($k, $v) = each($data)) {
                        if (empty($idata)) {
                            $idata = "'$v'";
                        } else {
                            $idata .= ",'$v'";
                        }
                    }

                } else {
                    //为字符串
                    $idata = $data;
                }
                $sqlStr = "insert into $table values ($idata)";

            }
            return $this->link->exec($sqlStr);

            if($this->link->exec($sqlStr))
            {
             return $this->link->lastinsertid();
            }
            return 0;
        }

        public function insert_sql($field,$values,$table = ""){
            $table = empty($table) ? $this->table : ($this->prefix . $table);
            $sqlStr = "insert into ".$table."(".$field.") values (".$values.")";
            return $this->link->exec($sqlStr);
        }

        /**
         * 数据删除
         * 参数:sql条件
         * @param $where
         * @return int
         */
        public function delete($where , $table = '')
        {
            $table = empty($table) ? $this->table : ($this->prefix . $table);

            $sqlStr = "delete from $table where $where";
            return $this->link->exec($sqlStr);
        }

        public function create($where = '1', $field = "*", $table = '')
        {

            $table = empty($table) ? $this->table : ($this->prefix . $table);

            $sqlStr = "select $field from $table where $where";

            return $sqlStr;
        }


        public function query($sql)
        {
            $rarr = array();
            $rt =  $this->link->query($sql);
            while ($rt && $arr = $rt->fetch(PDO::FETCH_ASSOC))
            {
                array_push($rarr, $arr);
            }
            return $rarr;
        }
        /**
         * 关闭MySQL连接
         * @return bool
         */
        public function close()
        {
            return mysql_close($this->link);
        }

    }


    /**
    ** 控制
    **/
    class control
    {
        public function __construct()
        {
            $this->request_init();
        }

        function request_init()
        {
            if(isset($_GET['m'])) $mod = $_GET['m'];
            else $mod = 'api';
            if ($mod) {
                //$mod = $_GET['m'];
                if (isset($_REQUEST['a'])) {
                    $act = $_REQUEST['a'];
                } else {
                    $act = 'default';
                }
                if (isset($_GET['class'])) {
                    $class = $_GET['class'];
                } else {
                    $class = "";
                }


                if (class_exists($mod)) {
                    try {
                        $instance = new $mod();
                        if(method_exists($mod, "do".$act)) {
                            if ($this->authenticate($instance,$act)) {
                                $act = "do".$act;
                                try {
                                    $result = $instance->$act();
                                }
                                catch(Exception $error) {
                                    die($error->getMessage());
                                }
                            } else {
                                die("You do not have access to the requested page!");
                            }
                        }else{
                            die("ERROR:'$act' <br/>An valid method for your request was not found");
                        }
                    }
                    catch(Exception $error) {
                        die($error->getMessage());
                    }
                } else {
                    die("An valid module for your request was not found");
                }
            }
        }

        function authenticate($c,$m)
        {
            return (!empty($c->checkMethod))?in_array($m,$c->checkMethod):true;
        }
    }

    class logger {
        public static function json($v , $one = false){

            if($one){
                if(count($v)>=1) logger::trace(json_encode($v[0]));
            }else
                logger::trace(json_encode($v));
        }

        public static function trace($v)
        {
            logger::process($v);
        }

        private static function process($v){
            $type = $_SERVER["HTTP_ACCEPT"];
            if(strpos($type , "/json")){
                header("Content-Type:application/json; charset=utf-8");
            }elseif(strpos($type , "/javascript")){
                header("Content-Type:text/javascript; charset=utf-8");
                if(!empty($_GET['callback'])){
                    $callback = $_GET['callback'];
                    $v = $callback."(".$v.")";
                }
            }
            echo($v);
            exit();
        }

        public static function errorPower()
        {
            $v = '{"status":-1,"info":"power request!"}';
            logger::process($v);
        }

        public static function info($code , $info ,$obj = false)
        {
            if($obj) $v = '{"status":"'.$code.'","detail":'.$info.'}';
            else $v = '{"status":"'.$code.'","detail":"'.$info.'"}';
            logger::process($v);
        }

        public static function success($info , $obj = false)
        {
            if($obj) $v = '{"status":0,"detail":'.$info.'}';
            else $v = '{"status":0,"detail":"'.$info.'"}';
            logger::process($v);
        }


        public static function error($info,$code='-1')
        {
            $v = '{"status":"'.$code.'","detail":"'.$info.'"}';
            logger::process($v);
        }
    }

	class api
	{
		private $db;

		function __construct()
		{
			$this->db = new D();
		}

		function dodefault(){
            $token = $_POST["token"];
            $data  = $_POST["data"];
            if($token && $data){
                $data_arr = explode(" " , $data);
                for( $i=0; $i<count($data_arr); $i++){
                    $data_arr[$i] = base64_decode($data_arr[$i]);
                }

                $value = "'".$token."','".date("Y-m-d H:i:s")."','".implode("','" , $data_arr)."'";
                $field = '`token`,`create_time`,`version`,`uptime`,`sessions`,`processes`,`processes_array`,`file_handles`,`file_handles_limit`,`os_kernel`,`os_name`,`os_arch`,`cpu_name`,`cpu_cores`,`cpu_freq`,`ram_total`,`ram_usage`,`swap_total`,`swap_usage`,`disk_array`,`disk_total`,`disk_usage`,`connections`,`nic`,`ipv4`,`ipv6`,`rx`,`tx`,`rx_gap`,`tx_gap`,`load`,`load_cpu`,`load_io`,`ping_cn_north`,`ping_cn_east`,`ping_cn_south`,`ping_cn_west`';
                $this->db->insert_sql($field, $value,'status');
            }
            echo('success');
		}

        // 退出，清除当次token
        function dosignout(){
        	$user = $_REQUEST["user_name"];
            $token = $_REQUEST["token"];

            $rs = $this->db->delete("user_name='".$user."' and token='".$token."'");
            if($rs){
            	logger::success('success');
            }else{
            	logger::success('user_name or token wrong');
            }

        }
	}

    date_default_timezone_set('PRC');
    session_start();
    new control();
?>